let ad_sdk_global = null
let global_data = {
  videoId: '',
  rewardVideoIndex: 0,
  rewardVideoArr: [], // 激励视频广告
  requestNum: 0
}
const initVideoAdvSdk = () => {
  ad_sdk_global = AD_SDK.ad_sdk_global
  global_data.rewardVideoArr = ad_sdk_global.adNewPostionConfig.ad_encourage
    ? AD_SDK.sortArray(ad_sdk_global.adNewPostionConfig.ad_encourage.split(','))
    : []
}
const setCommonParams = () => {
  return {
    id: global_data.videoId,
    ad_network: 1,
    ad_type: '视频',
    ad_style: '',
    scenario: '厂商广告联盟',
    popName: '广告池',
    popGroupName: '广告池',
    type: 'manu_ad',
    scene: '自动请求',
    adTurn: global_data.requestNum,
    requestNum: global_data.requestNum,
  }
}
// 播放预加载激励视频
const playVideoReward = () => {
  const videoAd = ad_sdk_global.preVideoAd
  if (videoAd && ad_sdk_global.preloadVideo) {
    AD_SDK.ad_sdk_global.videoPlaying = true
    var param = setCommonParams()
    AD_SDK.uploadAdInfo('take', param)
    videoAd.show()
    AD_SDK.uploadAdInfo(
      'show',
      Object.assign(param, { result: '渲染完成' })
    )
    AD_SDK.hideBannerAdv()
  } else {
    console.log('Rewardvideo+++++++++++++无预加载实时请求')
    getVedioAdv()
  }
}
/**
 * 取激励视频广告id
 */
const getNextRewardVideoId = () => {
  let rewardVideoId = ''
  if (global_data.rewardVideoIndex >= global_data.rewardVideoArr.length) {
    global_data.rewardVideoIndex = 0
  }
  rewardVideoId = global_data.rewardVideoArr[global_data.rewardVideoIndex]
  global_data.rewardVideoIndex++
  return rewardVideoId
}
/**
 * 展示激励视频
 * @param obj.scenario 获取的广告场景
 * @param obj.success 视频广告播放完成回调
 * @param obj.popGroupName 获取的广告场景
 * @param obj.popName 视频广告播放完成回调
 * @param obj.fail 视频广告播放失败回调
 * @param obj.incomplete 视频广告播放未完成回调
 */
function getVedioAdv(obj, isPreload = false, isReload = false) {
  console.log(
    ad_sdk_global.rewardFlag,
    isPreload,
    ad_sdk_global.preloadVideo,
    'Rewardvideo+++++++++++++开始'
  )
  if (ad_sdk_global.rewardFlag && !isReload) {
    return
  }
  AD_SDK.ad_sdk_global.rewardFlag = true
  if (isPreload && ad_sdk_global.preloadVideo) {
    console.log('已预加载到视频广告')
    return
  }
  global_data.videoId = getNextRewardVideoId()
  return new Promise(async (resolve, reject) => {
    if (!ad_sdk_global.serviceAd || !global_data.videoId) {
      obj && obj.fail && obj.fail('不支持广告或未配置广告id')
      reject('不支持广告或未配置广告id')
      return
    }
    global_data.requestNum++
    var param = setCommonParams()
    AD_SDK.uploadAdInfo(
      'request',
      Object.assign(param, { result: '发起请求' })
    )
    console.log(param, 'Rewardvideo+++++++++++++发起请求')
    let videoAd = await require('@service.ad').createRewardedVideoAd({
      adUnitId: global_data.videoId,
    })
    if (isPreload) {
      AD_SDK.ad_sdk_global.preVideoAd = videoAd
    }
    videoAd.onLoad(function (res) {
      console.log(res, 'Rewardvideo+++++++++++++')
      AD_SDK.ad_sdk_global.rewardFlag = false
      AD_SDK.ad_sdk_global.preloadVideo = isPreload ? true : false
      param.result = '有广告'
      AD_SDK.uploadAdInfo('request', param)
      if (!isPreload) {
        AD_SDK.ad_sdk_global.videoPlaying = true
        AD_SDK.uploadAdInfo('take', param)
        videoAd.show()
        AD_SDK.uploadAdInfo(
          'show',
          Object.assign(param, { result: '渲染完成' })
        )
        AD_SDK.hideBannerAdv()
        obj &&
          obj.request &&
          obj.request({ msg: '加载成功', videoId: global_data.videoId })
      } else {
        obj &&
          obj.preloadSuccess &&
          obj.preloadSuccess({
            msg: '预加载成功',
            videoId: global_data.videoId,
          })
      }
      videoAd.offError()
      videoAd.offLoad()
    })
    let videoFlag = false
    videoAd.onError(function (error) {
      console.log(error, 'Rewardvideo+++++++++++++error')
      AD_SDK.ad_sdk_global.rewardFlag = false
      if (videoFlag) {
        return
      }
      videoFlag = true
      param.result = `无广告${error.errCode ? error.errCode : '错误码获取失败'}`
      AD_SDK.uploadAdInfo('request', param)

      obj &&
        obj.fail &&
        obj.fail({ msg: '请求失败', videoId: global_data.videoId })
      AD_SDK.uploadAdInfo('take', param)
      videoAd.offError()
      videoAd.offLoad()
      // 连续请求在失败次数之内
      if (isPreload && obj.requestNum < 4) {
        obj.requestNum++
        getVedioAdv(obj, isPreload, true)
      }
      reject({ msg: '请求失败', videoId: global_data.videoId })
    })
    videoAd.load()
    videoAd.onClose((data) => {
      AD_SDK.ad_sdk_global.preloadVideo = false
      AD_SDK.ad_sdk_global.videoPlaying = false
      if (data.isEnded) {
        AD_SDK.uploadAdInfo(
          'render',
          Object.assign(param, { result: '播放完成' })
        )
        obj &&
          obj.success &&
          obj.success({ msg: '播放完成', videoId: global_data.videoId })
        resolve({ msg: '播放完成', videoId: global_data.videoId })
      } else {
        AD_SDK.uploadAdInfo(
          'render',
          Object.assign(param, { result: '播放未完成' })
        )
        obj &&
          obj.incomplete &&
          obj.incomplete({ msg: '播放未完成', videoId: global_data.videoId })
        reject({ msg: '播放未完成', videoId: global_data.videoId })
      }
      videoAd.offClose()
      // 关闭视频，重新请求
      if (isPreload) {
        AD_SDK.ad_sdk_global.rewardTimer = setTimeout(() => {
          obj.requestNum = 0
          getVedioAdv(obj, isPreload, true)
        }, 300)
      }
    })
  })
}
export { initVideoAdvSdk, playVideoReward, getVedioAdv }
